//对象克隆需要处理的四个问题
//1.clone()在Object中被protected修饰，要重写clone()方法，在其中用super调用
//2.clone()会抛出异常CloneNotSupportedException，要在方法中处理
//3.clone()返回类型是Object，使用时要向下转型
//4.类要先实现Cloneable接口，才可以被克隆

class Money implements Cloneable{
    double money = 19.9;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

class Person implements Cloneable {
    public int age;
    public Money m;

    public Person(int age) {
        this.age = age;
        this.m = new Money();
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        //浅拷贝
        //return super.clone();

        //深拷贝
        Person tmp = (Person) super.clone();
        tmp.m = (Money) this.m.clone();
        return tmp;
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", m=" + m +
                '}';
    }
}


public class Test {
    public static void main(String[] args) throws CloneNotSupportedException {
        Person person1 = new Person(18);
        Person person2 = (Person) person1.clone();
        System.out.println(person1.m.money);
        System.out.println(person2.m.money);
        System.out.println("=============");
        person2.m.money = 99.9;
        System.out.println(person1.m.money);
        System.out.println(person2.m.money);
    }
}


